package com.xh.facerecognition.sdk.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.xh.facerecognition.sdk.FaceRecognition;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class FaceUtils {

    public static String RECOGNITION_URL_END = "/FaceApp/appFaceRecognize/";
    public static String REGISTER_URL_END = "/FaceApp/appRegisterUser/";

    private static Call call;

    public static Call requestRecognition(String url, final File file, final OnFaceCallback callback) {
        Log.d("FaceRecognitionSDK", "requestRecognition url="+url);
        if (callback != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onStart();
                }
            });
        }

        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("head_file", file.getName(), fileBody)
//                .addFormDataPart("id_number", idcard)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .addHeader("requestType", "zuul")
                .post(requestBody)
                .build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(15, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(15, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(15, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Log.e("FaceRecognitionSDK", "requestRecognition onFailure:"+e.getMessage());
                file.delete();
                if (callback != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            callback.onError(getErrorMsg(e));
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                file.delete();
                final String uploadResult = response.body().string();// 把response转换成string
                try {
                    //{"result_code": 100, "id_number": "123456789012345678"}
                    //{"result_code": 101}
                    JSONObject jsonObj = new JSONObject(uploadResult);
                    final int resultCode = jsonObj.getInt("result_code");
                    final String idNumber = jsonObj.getString("id_number");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (resultCode == 100) {
                                callback.onSuccess(idNumber);
                            } else if (resultCode== 101) {
                                callback.onError("请求中未带有图片");
                            } else if (resultCode == 102) {
                                callback.onError("图片中未检测到人脸");
                            } else if (resultCode == 103) {
                                callback.onError("未匹配到任何人脸，可能是未录入");
                            } else {
                                callback.onError("未知错误:"+uploadResult);
                            }
                        }
                    });
                } catch (Exception e) {
                    Log.e("FaceRecognitionSDK", "requestRecognition onResponse result="+uploadResult+" Exception="+e.getMessage());
                    if (callback != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError("返回的数据格式错误");
                            }
                        });
                    }
                }
            }
        });
        return call;
    }

    private static String getErrorMsg(IOException e) {
        String message;
        if (e instanceof SocketTimeoutException) {
            message = "网络连接超时，请检查您的网络状态，稍后重试！";
        } else if (e instanceof ConnectException) {
            message = "网络连接异常，请检查您的网络状态，稍后重试！";
        } else if (e instanceof ConnectTimeoutException) {
            message = "网络连接超时，请检查您的网络状态，稍后重试！";
        } else if (e instanceof UnknownHostException) {
            message = "网络连接异常，请检查您的网络状态，稍后重试！";
        } else {
            message = e.getMessage();
        }
        return message;
    }

    public interface OnFaceCallback<T> {
        void onStart();
        void onSuccess(T data);
        void onError(String error);
    }

    public interface OnResultCallback {
        void onResult(String facePath);
        void onError(String error);
    }


    public static String saveBitmapFile(Context context, Bitmap bitmap){
        String defaultPath = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString();
        String imagePath = defaultPath + "/face_export" + System.currentTimeMillis() + ".jpg";
        File file=new File(imagePath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
            bos.flush();
            bos.close();
            return imagePath;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static final Handler HANDLER = new Handler(Looper.getMainLooper());
    public static void runOnUiThread(final Runnable runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run();
        } else {
            HANDLER.post(runnable);
        }
    }
}
